﻿let arr_time = ["09:00-10:20", "10:40-12:00", "12:30-13:50", "14:00-15:20", "15:30-16:50", "17:00-18:20", "19:00-20:20", "20:30-21:50"];
let courseInfo = [];
let myCourse = [];
let studentInfo = {};

//初始化
function init(callback) {
  getSetUpCourses(stu_id)
  getMyCourse(stu_id)
  getStudentInfo()
  callback && callback()
}

init()
this.isShowBtnGroup(false)

/**
 *获取开设的课程
 * @param {*} stu_id
 */
async function getSetUpCourses(stu_id) {
  const result = await request({
    url: 'Student/getSetUpCourses',
    data: { stu_id }
  })
  $('#list').html(this.courseList(result.courses))
}

//获取个人信息
async function getStudentInfo() {
  const result = await request({
    url: 'User/getStudentInfo',
    data: { id: stu_id}
  })
  studentInfo = result.student;
  console.log(studentInfo)
  $("#userId").text(studentInfo.user_id)
  $("#userName").text(studentInfo.name)
  $("#choose_num").text(studentInfo.choose_num)
  $("#chose_num").text(studentInfo.chose_num)
  $("#need").text(studentInfo.choose_num - studentInfo.chose_num)
}

/**
 * 根据id获取个人已选课程
 * @param {string} id 
 */
async function getMyCourse(id) {
  const result = await request({
    url: 'Student/getMyCourse',
    data: { id }
  })
  myCourse = result.courses
  $('#myList').html(this.courseList(result.courses))
  $('#myTbody').html(this.myTable(result.courses))
}

/**
 * 生成课程列表
 * @param {object} courses 
 */
function courseList(courses) {
  let elem = "";
  for (let item of courses) {
    elem += this.MyButton(item)
  }
  return elem;
}

/**
 * 生成表格
 * @param {object} courses 
 * @param {Boolean} radio  是否生成radio 
 */
function myTable(courses, radio = false) {
  let elem = "";
  let len = courses.length;
  for (let i = 0; i < 8; i++) {
    for (let j = 0; j < 6; j++) {

      if (j == 0) {
        elem += "<tr><td width=" + 120 + ">" + arr_time[i] + "</td>";
        continue;
      }

      let isIn = false;
      for (let z = 0; z < len; z++) {
        let newCourse = courses[z]
        if (i == newCourse["time"] && j == newCourse["day"]) {
          elem += "<td class='tao_table_hover'>" + newCourse['name'] + "<br>" + newCourse['class_course_id'] + "  " + newCourse['start'] + "-" + newCourse['last'] + "<br>" + this.MyRadio(newCourse['course_id'], newCourse['class_course_id'], radio, newCourse['isSelect'], newCourse['count'] - newCourse.choose) + "</td>";
          isIn = true;
          break;
        }
      }

      if (!isIn) {
        elem += "<td class='tao_table_hover'>" + "" + "</td>";
      }
    }
    elem += "</tr>";
  }
  return elem;
}

/**
 * 生成radio
 * @param {string} name 
 * @param {string} id 
 * @param {Boolean} radio 
 */
function MyRadio(name, id, radio, isSelect, count) {
  if (isSelect) {
    return radio ? `<label class='radio-inline'><input type='radio' class='radio' name='${name}' id='${id}' value='${id}' checked aria-label='...'></label> ${count}人` : '';
  } else {
    return radio ? `<label class='radio-inline'><input type='radio' class='radio' name='${name}' id='${id}' value='${id}' aria-label='...'></label> ${count}人` : '';
  }
}

/**
 * 生成button
 * @param {object} course 
 */
function MyButton(course) {
  let btn = `<button type='button' id='${this.soleId(course)}' class='btn btn-link tao_btn' onclick="btnClick('${course.course_id}')">${course.name}</button>`
  return btn;
}

/**
 * 生成唯一id
 * @param {object} course 
 */
function soleId(course) {
  return course.course_id + "-" + Number(Math.random().toString().substr(3, 3) + Date.now()).toString(36);
}

/**
 * button点击事件的回调函数
 * @param {string} id
 * @return {false}  阻止页面刷新 
 */
function btnClick(id) {
  this.getCourseClassById(id)
  this.isShowBtnGroup(true)
  return false;
}

/**
 * 根据课程号获取开设的班级
 * @param {string} id 
 */
async function getCourseClassById(id) {
  const result = await request({
    url: 'Student/getCourseClassById',
    data: { id, stu_id }
  })
  courseInfo = result.courses;
  $("#tbody").html(this.myTable(result.courses, true))
}

//监听选课按钮点击
$('#choose').click((e) => {
  e.preventDefault()
  let selectId = $("input:checked").val()
  let selected = selectId ? courseInfo.find(item => item.isSelect) : '';
  let nowSelect = selectId ? courseInfo.find(item => item.class_course_id == selectId) : '';

  if(studentInfo.choose_num <= studentInfo.chose_num) return alert('你的选修学分已用完')
  if(!canSelect(nowSelect)) return alert('课程冲突')
  if (nowSelect && nowSelect.count > 0) {
    selected = selected || {}
     if (selected.class_course_id != selectId) {
      this.selectCourse(selectId, selected.class_course_id)
    }
  } else {
    console.log('课程可选空位小于0')
  }
})

function canSelect(nowSelect) {
  let selected = myCourse.filter(item => {
    return item.day == nowSelect.day && item.time == nowSelect.time
  })[0]
  if(selected) return false
  return true
  // if(!selected) return true
  // if(selected.last >= nowSelect.start 
  // || selected.last >= nowSelect.start) return false
  // return true
}

//发送选课请求
async function selectCourse(selectId, selected) {
  const result = await request({
    url: 'Student/addSelectCourse',
    data: {
      class_course_id: selectId,
      stu_id,
      selected,
      time: new Date().getTime()
    }
  })
  this.init()
  this.getCourseClassById(courseInfo[0].course_id)
}

//监听退课按钮点击
$('#drop').click((e) => {
  e.preventDefault()
  let selectId = $("input:checked").val()
  let selected = selectId ? courseInfo.find(item => item.isSelect) : '';
  selected = selected && selected.class_course_id
  if (selected) {
    this.dropCourse(selected)
  }
})

//发送退课请求
async function dropCourse(selected) {
  const result = await request({
    url: 'Student/deleteSelectCourse',
    data: {
      class_course_id: selected,
      stu_id
    }
  })
  this.init()
  this.getCourseClassById(courseInfo[0].course_id)
}

$("#refresh").click((e) => {
  e.preventDefault()
  init(() => {
    this.isShowBtnGroup()
  })
})

//控制选课和退课按钮组的显示与隐藏
function isShowBtnGroup(showOrHide = false) {
  $("#btn_group").toggle(showOrHide)
}